package com.zjw.zy.coreui.dialog

import android.content.Context
import com.zjw.zy.base.BaseDialog
import android.content.DialogInterface
import android.widget.TextView
import com.zjw.zy.R
import com.zjw.zy.utils.ResourcesUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/10/20 16:18
 */
class LoadingDialog : BaseDialog {

    private val title: TextView? by lazy { findViewById(R.id.loading_dialog_title) }
    private var countDownDisposable: Disposable? = null

    private var titleTxt = ""

    private var count = -1
    private var countDownFinish: Runnable? = null

    constructor(context: Context) : super(context) {}
    protected constructor(context: Context, themeResId: Int) : super(context, themeResId) {}
    protected constructor(
        context: Context,
        cancelable: Boolean,
        cancelListener: DialogInterface.OnCancelListener?
    ) : super(context, cancelable, cancelListener) {
    }

    override fun onFindView() {
    }

    override fun onBindListener() {

    }

    override fun onBindValue() {
        if (count == -1) {
            title?.text = titleTxt
        } else {
            startCountDown()
        }
        setCanceledOnTouchOutside(false)
    }

    private fun startCountDown() {
        title?.text =
            ResourcesUtils.getString(R.string.loading_dialog_count_down, titleTxt, count)
        countDownDisposable =
            Observable.interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (count <= 0) {
                        countDownDisposable?.dispose()
                        countDownFinish?.run()
                        dismiss()
                        return@subscribe
                    }
                    title?.text =
                        ResourcesUtils.getString(
                            R.string.loading_dialog_count_down,
                            titleTxt,
                            --count
                        )
                }
    }

    private fun stopCountDown() {
        countDownDisposable?.dispose()
        count = -1
        dismiss()
    }

    override fun onDetachedFromWindow() {
        stopCountDown()
        super.onDetachedFromWindow()
    }

    override fun onLayoutId(): Int {
        return R.layout.loading_dialog
    }

    fun title(title: String): LoadingDialog {
        titleTxt = title
        return this
    }

    fun enableCountDown(count: Int): LoadingDialog {
        this.count = count
        return this
    }

    fun countFinish(call: Runnable): LoadingDialog {
        countDownFinish = call
        return this
    }
}